﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;

namespace Tiscs.Practices.Web.Services.Client
{
    /// <summary>
    /// 用户登录操作。
    /// </summary>
    /// <typeparam name="T">用户信息类的类型。</typeparam>
    public sealed class SignInOperation<T> : AuthenticationOperation<T> where T : IPrincipal
    {
        /// <summary>
        /// 构造方法。
        /// </summary>
        /// <param name="client">身份验证客户端实例。</param>
        /// <param name="parameters">用户登录参数。</param>
        /// <param name="callback">异步操作执行完毕回调。</param>
        /// <param name="userState">用户状态。</param>
        internal SignInOperation(IAuthenticationServiceClient<T> client, SignInParameters parameters, Action<SignInOperation<T>> callback, object userState)
            : base(client, userState)
        {
            _callback = callback;
            _signInParameters = parameters;
        }

        /// <summary>
        /// 异步操作执行完毕回调。
        /// </summary>
        private readonly Action<SignInOperation<T>> _callback;

        /// <summary>
        /// 用户登录参数。
        /// </summary>
        private readonly SignInParameters _signInParameters;

        /// <summary>
        /// 获取用户登录参数。
        /// </summary>
        public SignInParameters SignInParameters
        {
            get
            {
                return _signInParameters;
            }
        }

        /// <summary>
        /// 开始执行异步操作。
        /// </summary>
        /// <param name="callback">异步操作执行完毕回调。</param>
        /// <returns>异步执行结果实例。</returns>
        protected override IAsyncResult BeginCore(AsyncCallback callback)
        {
            return Client.BeginSignIn(_signInParameters.UserName, _signInParameters.Password, _signInParameters.CustomData, _signInParameters.IsPersistent, callback, UserState);
        }

        /// <summary>
        /// 异步执行结束方法。
        /// </summary>
        /// <param name="result">异步执行结果实例。</param>
        /// <returns>异步操作的返回数据。</returns>
        protected override object EndCore(IAsyncResult result)
        {
            return Client.EndSignIn(result);
        }

        /// <summary>
        /// 执行结束方法。
        /// </summary>
        protected override void InvokeCompleteAction()
        {
            if (_callback != null)
            {
                _callback(this);
            }
        }
    }
}
